package com.kexun.servlet;

import com.kexun.service.impl.PublicServiceImpl;
import com.kexun.pojo.User;
import com.kexun.service.PublicService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/servletLogin")
public class Servletlogin extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //接收参数
        String num = request.getParameter("num");
        String pwd = request.getParameter("pwd");
        String role = request.getParameter("role");
        //对角色数据类型进行转换
        int roles = Integer.parseInt(role);

        //调用业务逻辑
        PublicService ps = new PublicServiceImpl();
//        System.out.println("账号："+num);
//        System.out.println("密码："+pwd);
//        System.out.println("角色: "+role);

        User user = ps.login(num);

        HttpSession session = request.getSession();


//request.setAttribute("user",user)?        El表达式在jsp可获得值的四种域对象（request，session，
        //判断结果，分发转向
        if(user != null){//1.账号正确
            if(user.getPassword().equals(pwd)){   //1 密码正确
                if(user.getRoleId() == roles){// 3角色匹配
                    session.setAttribute("user",user);
                    if(roles == 0){// 学生页面
                        request.getRequestDispatcher("student/stuMain.jsp").forward(request,response);
                    }else if(roles == 1){ // 老师页面
                        request.getRequestDispatcher("teacher/teaMain.jsp").forward(request,response);;
                    }else{//管理员页面
                        request.getRequestDispatcher("admin/adminMain.jsp").forward(request,response);;

                    }


                }else{ // 3 角色不匹配

                    request.setAttribute("msg","角色不匹配");
                    request.getRequestDispatcher("login.jsp").forward(request,response);
                }

            }else{// 2密码错误

                request.setAttribute("msg","密码错误");
                request.getRequestDispatcher("login.jsp").forward(request,response);
            }

        }else{// 1 账号错误
            request.setAttribute("msg","账号错误或不存在");
            request.getRequestDispatcher("login.jsp").forward(request,response);

        }





    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
